package com.we.flink.userlabelplatform.tag;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import com.alibaba.fastjson.JSONObject;
import com.we.flink.userlabelplatform.table.TableUserAudit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TagUserAudit {
    public long uid;
    public Integer last_audit_status;
    public Integer last_audit_time;
    public Integer last_audit_failed_time;
    public Integer last_audit_success_time;

    public static Logger LOG = LoggerFactory.getLogger(TagUserAudit.class);

    public TagUserAudit() {}

    public TagUserAudit(
            long uid,
            Integer last_audit_status,
            Integer last_audit_time,
            Integer last_audit_failed_time,
            Integer last_audit_success_time) {
        this.uid = uid;
        this.last_audit_status = last_audit_status;
        this.last_audit_time = last_audit_time;
        this.last_audit_failed_time = last_audit_failed_time;
        this.last_audit_success_time = last_audit_success_time;
    }

    public static TagUserAudit init(long uid) {
        return new TagUserAudit(uid, -1, -1, -1, -1);
    }

    public static SingleOutputStreamOperator<String> getFlatMapStream(
            StreamTableEnvironment tableEnv, StreamExecutionEnvironment env) {
        Table tableRes = tableEnv.sqlQuery(TableUserAudit.QUERYSQL);
        DataStream<Tuple2<Boolean, TableUserAudit>> inputStream =
                tableEnv.toRetractStream(tableRes, TableUserAudit.class);

        SingleOutputStreamOperator<String> out =
                inputStream
                        .filter(
                                new FilterFunction<Tuple2<Boolean, TableUserAudit>>() {
                                    @Override
                                    public boolean filter(Tuple2<Boolean, TableUserAudit> value)
                                            throws Exception {
                                        return value.f0;
                                    }
                                })
                        .uid("TagUserAudit-filter")
                        .keyBy(
                                new KeySelector<Tuple2<Boolean, TableUserAudit>, Long>() {
                                    @Override
                                    public Long getKey(Tuple2<Boolean, TableUserAudit> value)
                                            throws Exception {
                                        return value.f1.getUid();
                                    }
                                })
                        .flatMap(
                                new RichFlatMapFunction<Tuple2<Boolean, TableUserAudit>, String>() {
                                    ValueState<TagUserAudit> tableUserAuditVState;

                                    @Override
                                    public void open(Configuration parameters) throws Exception {
                                        tableUserAuditVState =
                                                getRuntimeContext()
                                                        .getState(
                                                                new ValueStateDescriptor<
                                                                        TagUserAudit>(
                                                                        "TableUserAuditVState",
                                                                        TagUserAudit.class));
                                    }

                                    @Override
                                    public void flatMap(
                                            Tuple2<Boolean, TableUserAudit> value,
                                            Collector<String> out)
                                            throws Exception {
                                        TagUserAudit tmpState = tableUserAuditVState.value();
                                        long uid = value.f1.getUid();
                                        int audit_status = value.f1.getAudit_status();
                                        int audit_time = value.f1.getAudit_time();
                                        TagUserAudit curState =
                                                (tmpState == null
                                                        ? TagUserAudit.init(uid)
                                                        : tmpState);

                                        JSONObject jsonObject = new JSONObject();
                                        jsonObject.put("uid", uid);
                                        if (curState.last_audit_time < audit_time) {
                                            curState.last_audit_time = audit_time;
                                            curState.last_audit_status = audit_status;
                                            jsonObject.put(
                                                    "last_audit_status",
                                                    (audit_status == -1 ? null : audit_status));
                                            jsonObject.put(
                                                    "last_audit_time",
                                                    (audit_time == -1 ? null : audit_time));
                                        }
                                        /** 防止乱序导致审核失败记录被丢弃 '状态：1审核中，2审核通过，3审核失败' */
                                        if (audit_status == 3
                                                && (curState.last_audit_failed_time < audit_time)) {
                                            curState.last_audit_failed_time = audit_time;
                                            jsonObject.put("last_audit_failed_time", audit_time);
                                        }

                                        if (audit_status == 2
                                                && (curState.last_audit_success_time
                                                        < audit_time)) {
                                            curState.last_audit_success_time = audit_time;
                                            jsonObject.put("last_audit_success_time", audit_time);
                                        }

                                        if (jsonObject.size() > 1) {
                                            out.collect(jsonObject.toString());
                                            tableUserAuditVState.update(curState);
                                        }
                                    }
                                });
        return out;
    }

    public long getUid() {
        return uid;
    }

    public Integer getLast_audit_status() {
        return last_audit_status;
    }

    public Integer getLast_audit_time() {
        return last_audit_time;
    }

    public Integer getLast_audit_failed_time() {
        return last_audit_failed_time;
    }
}
